IF(EXISTS(SELECT 1 FROM Sysobjects WHERE name = 'fn_Split' AND xtype = 'TF'))
BEGIN
	DROP FUNCTION fn_Split
END
GO

CREATE FUNCTION fn_Split(
    @LIST      VARCHAR(4000),
	@DELIMITER VARCHAR(5)
) 
RETURNS @TABLEOFVALUES TABLE 
(   
	[VALUE] VARCHAR(4000) 
) 
AS 
BEGIN
DECLARE @LENSTRING INT 
 
WHILE LEN( @LIST ) > 0 
    BEGIN 
    
    SELECT @LENSTRING = 
        (CASE CHARINDEX( @DELIMITER, @LIST ) 
            WHEN 0 THEN LEN( @LIST ) 
            ELSE ( CHARINDEX( @DELIMITER, @LIST ) -1 )
        END
        ) 
                                
    INSERT INTO @TABLEOFVALUES 
        SELECT SUBSTRING( @LIST, 1, @LENSTRING )
                
    SELECT @LIST = 
        (CASE ( LEN( @LIST ) - @LENSTRING ) 
            WHEN 0 THEN '' 
            ELSE RIGHT( @LIST, LEN( @LIST ) - @LENSTRING - 1 ) 
        END
        ) 
    END
	RETURN 
END
GO

IF (EXISTS(SELECT 1 FROM Sysobjects WHERE xtype = 'P' AND name = 'wp_ActualizarRecorridas'))
BEGIN
	DROP PROCEDURE wp_ActualizarRecorridas
END
GO

CREATE PROCEDURE wp_ActualizarRecorridas
	@idAcceso AS int,
	@idRecorrida AS varchar(4000)
AS

DELETE 
FROM nuevositio.dbo.Acceso_recorrida
WHERE idAcceso = @idAcceso


INSERT INTO nuevositio.dbo.Acceso_recorrida
        ( idAcceso ,
          idRecorrida ,
          idExpediente
        )
SELECT @idAcceso, RTRIM(LTRIM(VALUE)), NULL
FROM fn_Split(@idRecorrida, ',')

